package com.xm.springboot.controller;

import com.xm.springboot.dao.DepartmentDao;
import com.xm.springboot.dao.EmployeeDao;
import com.xm.springboot.entities.Department;
import com.xm.springboot.entities.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.logging.Logger;

@Controller
public class EmployeeController {
    private static final Logger logger = Logger.getGlobal();

    @Autowired
    EmployeeDao employeeDao;

    @Autowired
    DepartmentDao departmentDao;

    /**
     * 查询所有员工
     */
    @GetMapping(path = "/emps")
    public String list(Model model) {
        Collection<Employee> emps = employeeDao.getAll();

        // 放在请求域中
        model.addAttribute("emps", emps);
        /**
         * thymeleaf 默认拼接字符串
         * ThymeleafProperties
         * 	DEFAULT_PREFIX = "classpath:/templates/";
         * 	DEFAULT_SUFFIX = ".html";
         * 	即 "classpath:/templates/xxx.html"
         */
        return "/emp/list";
    }


    /**
     * 添加员工页面
     */
    @GetMapping(path = "/emp")
    public String toAddEmp(Model model) {
        // 取出部门
        Collection<Department> departments = departmentDao.getDepartments();

        model.addAttribute("depts", departments);

        return "/emp/add";
    }


    /**
     * 员工添加
     * SpringMVC 自动将请求参数和入参对象的属性进行一一绑定, 要求请求参数名字JavaBean入参对象属性名一致
     */
    @PostMapping(path = "/emp")
    public String addEmp(Employee employee) {

        Logger.getGlobal().info(employee.toString());

        employeeDao.save(employee);

        // 来到员工列表页面
        // redirect: 重定向
        // forward: 转发
        return "redirect:/emps";
    }

    /**
     * 跳转到修改页面
     * @return
     */
    @GetMapping("/emp/{id}")
    public String toEditPage(@PathVariable("id") Integer id, Model model) {
        Employee employee = employeeDao.get(id);
        model.addAttribute("emp", employee);
        Collection<Department> departments = departmentDao.getDepartments();
        model.addAttribute("depts", departments);

        return "/emp/add";
    }

    /**
     * 员工修改
     * @param employee
     * @return
     */
    @PutMapping(path = "/emp")
    public String updateEmp(Employee employee) {
        logger.info(employee.toString());

        employeeDao.save(employee);

        return "redirect:/emps";
    }

    /**
     * 删除员工
     */
    @DeleteMapping(path = "/emp/{id}")
    public String deleteEmp(@PathVariable("id") Integer id) {
        logger.info(String.valueOf(id));

        employeeDao.delete(id);
        return "redirect:/emps";
    }
}